package simplenotepad;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;

public class SimpleNotepad extends JFrame implements ActionListener {
    JMenuItem saveFile = new JMenuItem("Save");
    JMenuItem openFile = new JMenuItem("Open");
    JTextArea textArea = new JTextArea();

    public SimpleNotepad() {
        super("Simple Notepad");
        textArea.setBounds(5, 5, 790, 590);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textArea.setEditable(true);
        JScrollPane textPane = new JScrollPane(textArea);
        add(textPane);

        saveFile.addActionListener(this);
        openFile.addActionListener(this);

        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Menu");
        menu.add(saveFile);
        menu.add(openFile);
        menuBar.add(menu);
        setJMenuBar(menuBar);

        setSize(800, 600);
        setVisible(true);
    }

    public static void main(String[] args) {
        SimpleNotepad app = new SimpleNotepad();
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser fileChooser;
        File file;
        if (e.getSource() == openFile) {
            fileChooser = new JFileChooser();
            System.out.println("mi_open clicked");
            if (fileChooser.showOpenDialog(this) == JFileChooser.OPEN_DIALOG) {
                file = fileChooser.getSelectedFile();
                try {
                    char[] context = new char[819200];
                    InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
                    reader.read(context);
                    textArea.setText(new String(context, 0, (int) file.length()));
                } catch (Exception error) {
                    System.out.println(error);
                }
            }
        }
        if (e.getSource() == saveFile) {
            fileChooser = new JFileChooser();
            System.out.println("mi_save clicked");
            if (fileChooser.showOpenDialog(this) == JFileChooser.OPEN_DIALOG) {
                file = fileChooser.getSelectedFile();
                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
                    writer.write(textArea.getText());
                    writer.close();
                } catch (Exception error) {
                    System.out.println(error);
                }
            }
        }
    }
}
